package com.itcast.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 安全认证登录，未登录不允许访问任何资源
 */
@WebFilter("/*")//拦截所有请求以便进行判断
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
      //判断session中是否含有登陆者信息,先获取session
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        Object username = request.getSession().getAttribute("username");
        //若请求的路径就是去登录的，那么也可以放行让他登录
        String uri = request.getRequestURI();
        //先判断是不是去登录的
        if(uri.contains("login") || uri.contains("css") || uri.contains("/js") || uri.contains("img") || uri.contains("fonts")){
            chain.doFilter(request,response);
        }else {//不是就再判断是不是已经登录过了
        if(username!=null){//若session中有值则表示登录过了，放行
            chain.doFilter(request,response);
        }else {
            //没有就去登录
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }}

    @Override
    public void destroy() {

    }
}
